package util;

import java.io.File;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.function.Function;
import java.util.jar.JarFile;
import java.util.stream.Collectors;

/**
 * @author yexi
 */
public class ProjectUtils {

    /**
     * 获取当前项目依赖的所有jar包的名称
     */
    public static List<String> getDependenciesJarNames() {
        try {
            // 获取当前类加载器
            ClassLoader classLoader = ClassLoader.getSystemClassLoader();
            // 获取所有的 MANIFEST.MF
            Enumeration<URL> urls = classLoader.getResources("META-INF/MANIFEST.MF");
            ArrayList<URL> urlList = Collections.list(urls);
            return urlList.stream()
                    .map(url -> {
                        try {
                            URLConnection connection = url.openConnection();
                            if (connection instanceof JarURLConnection) {
                                return ((JarURLConnection) connection).getJarFile().getName();
                            }
                            try (JarFile jarFile = new JarFile(new File(url.toURI()))) {
                                return jarFile.getName();
                            }
                        } catch (Exception ex) {
                            return null;
                        }
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
